<template>
  <div id="trainIndex">
    <el-dialog title="人员信息详情" :visible.sync="personDetailVisible" width="80%" top="20px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <personInfo :personId='personId' :hidemoredetail="true"></personInfo>
    </el-dialog>
    <el-dialog :title="addFormTitle" :visible.sync="addFormVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" :append-to-body="true" >
      <additional-person-detail :deptId="deptId" @refreshRecommented="refreshRecommented(false)" :timestamp="timestamp1" :personId='personId'  />
    </el-dialog>
    <section class="wboxs" style="type===padding:0 ;border:0">
      <div style="float:left;margin:10px 10px 0;">
        <el-form :inline="true" :model="filters">
          <!-- <div :style="'height:'+(type==='filed'?110:50)+'px;overflow:hidden'"> -->
          <div>
            <el-form-item label="">
              <el-select v-model="filters.team" placeholder="请选择" style="width:110px" @change="searchPrj" v-if="!deptId&&userType!==2">
              <!-- <el-select v-model="filters.team" placeholder="请选择" style="width:110px" @change="searchPrj"> -->
                <el-option label="全部" :value="null"></el-option>
                <el-option v-for="(item, index) in teams" :key="'team'+index" :label="item" :value="index+1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="filters.unit" style="width:150px;" placeholder="单位名称" @keyup.enter.native="searchPrj"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="filters.name" style="width:170px;" placeholder="姓名" @keyup.enter.native="searchPrj"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="filters.idCardNo" style="width:160px;" placeholder="身份证号" @keyup.enter.native="searchPrj"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchPrj" icon="el-icon-search">查询</el-button>
            </el-form-item>

              <el-button type="success" style="float:right" v-if="type==='filed'" @click="handleEdit()" icon="el-icon-plus">手动添加人选</el-button>
          </div>
        </el-form>
      </div>
    </section>
    <section class="wboxd" style="margin-top:10px':'width:auto;border:0;margin-top:10px">
      <el-table :row-class-name="rowStyle" :data="personList" highlight-current-row v-loading="listLoading" style="width: 100%;border-right:1px solid #74A6CC" border>
        <el-table-column prop="pindex" label="序号" width="60" align="left">
          <template slot-scope="scope">
            <span>{{scope.row.pindex}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" min-width="90" />
        <el-table-column prop="name" label="姓名" width="90" />
        <el-table-column prop="job" label="职务" width="200" align="center">
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100" align="center">
        </el-table-column>
        <el-table-column prop="partyMember" label="是否党员" width="50" align="center">
          <template slot-scope="scope" >
            {{scope.row.partyMember?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column prop="jobDate" label="任相当层次职务职级时间" width="120" align="center">
          <template slot-scope="scope" >
            {{formatJobDate(scope.row.jobDate)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" v-if="type==='recommended'">
          <template slot-scope="scope">
              <el-button size="small" @click="handleEdit(scope.row.id)" type="primary" style="margin:10px 0 10px 0">修改</el-button>
              <el-button type="success" size="small" @click="addToCandidate(scope.row)" :loading="addLoading" style="margin:10px 0">选为建议人选</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" v-if="type==='official'">
          <template slot-scope="scope">
            <template>
              <el-button size="small" @click="handleEdit(scope.row.id)" type="primary" style="margin:10px 0 10px 0">修改</el-button>
              <el-button type="success" size="small" @click="addToCandidate(scope.row,1)" :loading="addLoading" style="margin:10px 0">选为参训人选</el-button>
              <el-button type="primary" size="small" @click="addToCandidate(scope.row,2)" :loading="addLoading" style="margin:10px 0">选为备选人选</el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" v-if="type==='filed'">
          <template slot-scope="scope">
            <template>
              <el-button size="small" @click="handleEdit(scope.row.id)" type="primary" style="margin:10px 0 10px 0">修改</el-button>
              <el-button type="success" size="small" @click="addToFiled(scope.row)" :loading="addLoading" style="margin:10px 0">新增培训</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination style="float:right" :total="totalnum" :page-size="pageSize" @current-change="handleCurrentChange" :current-page="pageNum" @size-change="handleSizeChange" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      </div>
    </section>
  </div>
</template>

<script>
import qs from 'qs'
import personInfo from '@/person/Detail.vue'
import additionalPersonDetail from './additionalPersonDetail.vue'
export default {
  components: {
    personInfo, additionalPersonDetail
  },
  watch: {
    timestamp: {
      handler (val) {
        if (val) {
          this.timestamp1 = val
          this.getList()
        }
      },
      immediate: true
    },
    deptId: {
      handler (val) {
        if (val) {
          this.getList()
        }
      },
      immediate: true
    },
    type: {
      handler (val) {
        if (val !== 'filed') {
          this.viewtype = 2
        }
      },
      immediate: true
    }
  },
  props: {
    type: null,
    deptId: null,
    classId: null,
    timestamp: null
  },
  data () {
    return {
      timestamp1: null,
      dateType: 1,
      personDetailVisible: false,
      personId: null,
      showManage: false,
      exportVisible: false,
      exportForm: {
        year: null,
        team: null
      },
      btnLoading: false,
      addFormTitle: '新增',
      loading: false,
      userType: null,
      showClassId: null,
      totalnum: 0,
      viewtype: 1,
      personList: [
      ],
      filters: {
        team: null,
        unit: '',
        name: '',
        idCardNo: ''
      },
      saveLoading: false,
      teams: ['机关司局', '直属单位', '派出机构'],
      yearlist: [],
      listLoading: false,
      pageNum: 1,
      pageSize: 20,
      changeSizeFlag: false,
      addLoading: false,
      classVisible: false,
      addFormVisible: false,
      addForm: {
        unit: '',
        name: '',
        idCardNo: '',
        age: '',
        job: '',
        level: '',
        partyMember: '',
        jobDate: '',
        trainingDate: '',
        trainingDateRemark: '',
        trainingYear: '',
        trainUnit: '',
        className: '',
        place: ''
      },
      addFormRules: {
        jobDate: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        trainUnit: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '必填项', trigger: 'blur' }
        ],
        place: [
          { required: true, message: '必填项', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    formatJobDate (str) {
      if (str) {
        if (str.length === 6 && /^[0-9]*$/.test(str)) { // yyyymm
          return str.substr(0, 4) + '.' + str.substr(4)
        }
        if (str.length === 8 && /^[0-9]*$/.test(str)) { // yyyymmdd
          return str.substr(0, 4) + '.' + str.substr(4, 2) + '.' + str.substr(6, 2)
        } else {
          return str
        }
      }
    },
    refreshRecommented () {
      this.addFormVisible = false
      this.getList()
    },
    rowStyle ({row, rowIndex}) {
      if (row.markYear) {
        return 'mark_class'
      }
      return ''
    },
    persondetail (id) {
      this.personDetailVisible = true
      this.personId = id
    },
    detail (idcardNo) {
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/jiben/getIdByIdCardNo?idcard=` + idcardNo)
        .then(response => {
          if (response.data.success) {
            if (response.data.result) {
              this.persondetail(response.data.result)
            } else {
              this.$message({
                message: '无此人选的干部全方位情况',
                type: 'error'
              })
            }
          } else {
            this.$message({
              message: '查询失败:无此人选的干部全方位情况',
              type: 'error'
            })
          }
        })
        .catch(() => {
          this.$message({
            message: '查询失败:无此人选的干部全方位情况',
            type: 'error'
          })
        })
    },
    exportData () {
      let para = {team: this.exportForm.team, year: this.exportForm.year}
      window.open(this.$http.defaults.baseURL + this.$http.defaults.trainingAPI + 'api/trainingBusFiledCandidate/getExport?' + qs.stringify(para))
    },
    handleExport () {
      this.exportForm.year = null
      this.exportForm.team = null
      this.exportVisible = true
    },
    handleIndex () {
      this.$router.push({name: `Train`})
    },
    handleAuth () {
      this.$router.push({name: `trainAuth`})
    },
    handleChart () {
      this.$router.push({name: `trainChart`})
    },
    isDate8 (sDate) {
      if (!/^[0-9]{8}$/.test(sDate)) {
        return false
      }
      var year, month, day
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      day = sDate.substring(6, 8)
      var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      if (year < 1700 || year > 2500) return false
      if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) iaMonthDays[1] = 29
      if (month < 1 || month > 12) return false
      if (day < 1 || day > iaMonthDays[month - 1]) return false
      return true
    },
    isDate6 (sDate) {
      if (!/^[0-9]{6}$/.test(sDate)) {
        return false
      }
      var year, month
      year = sDate.substring(0, 4)
      month = sDate.substring(4, 6)
      if (year < 1700 || year > 2500) return false
      if (month < 1 || month > 12) return false
      return true
    },
    submitForm () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          console.log(this.addForm.jobDate)
          if (!this.isDate8(this.addForm.jobDate) && !this.isDate6(this.addForm.jobDate) && this.addForm.jobDate) {
            this.$message({
              message: '任相当层次职务职级时间保存失败：格式有误，格式：20201001或202010',
              type: 'error'
            })
            return false
          }
          let para = {
            id: this.addForm.id,
            name: this.addForm.name,
            idCardNo: this.addForm.idCardNo,
            jobDate: this.addForm.jobDate,
            trainingDate: this.dateType === 1 ? this.addForm.trainingDate : '',
            trainingDateRemark: this.dateType === 2 ? this.addForm.trainingDateRemark : '',
            trainingYear: this.dateType === 2 ? parseInt(this.addForm.trainingYear) : (this.addForm.trainingDate ? this.dateFtt('yyyy', this.addForm.trainingDate) : ''),
            trainUnit: this.addForm.trainUnit,
            className: this.addForm.className,
            place: this.addForm.place
          }
          if (this.dateType === 2 && (!this.addForm.trainingDateRemark || !this.addForm.trainingYear)) {
            this.$message({
              message: '参训日期不明确时请填写参训日期描述和参训年份',
              type: 'error'
            })
            return false
          }
          if (this.dateType === 1 && !this.addForm.trainingDate) {
            this.$message({
              message: '请填写参训日期',
              type: 'error'
            })
            return false
          }
          this.addLoading = true
          this.$http.post(this.$http.defaults.trainingAPI + `api/trainingBusFiledCandidate/save`, para).then(response => {
            console.log(response.data.success)
            this.addLoading = false
            if (response.data.success === true) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.addFormVisible = false
              this.getList()
            } else {
              // console.log('保存失败:' + response.data.message)
              this.$message({
                message: '保存失败:' + response.data.message,
                type: 'error'
              })
            }
          }).catch((error) => {
            console.log(error)
            this.$message({
              message: '网络保存失败:' + error,
              type: 'error'
            })
            this.addLoading = false
          })
        }
      })
    },
    handleDel (id) {
      this.$confirm('确认删除该培训记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.btnLoading = true
        let para = {ids: [id]}
        this.listLoading = true
        this.$http.post(this.$http.defaults.trainingAPI + `api/trainingBusFiledCandidate/remove`, para).then(response => {
          this.btnLoading = false
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
      })
    },
    handleEdit (id) {
      this.timestamp1 = new Date().getTime()
      // this.loading = true
      this.addFormVisible = true
      if (id) {
        this.addFormTitle = '修改'
        this.personId = id
      } else {
        this.addFormTitle = '手动添加人选'
      }
    },
    handleAdd (data) {
      console.log(data)
      this.loading = true
      this.addFormVisible = true
      this.addFormTitle = '新增'
      this.addForm.unit = ''
      this.addForm.name = ''
      this.addForm.idCardNo = ''
      this.addForm.level = ''
      this.addForm.jobDate = null
      this.addForm.id = null
      this.dateType = 1
    },
    showClass (id) {
      this.showClassId = id
      this.classVisible = true
    },
    isPartyMember (text) {
      if (text) {
        if (text === '中共党员' || text === '预备党员') {
          return 1
        } else {
          return 0
        }
      } else {
        return ''
      }
    },
    handleSizeChange (val) {
      this.pageNum = 1
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.pageNum = val
      this.getList()
    },
    addToFiled (data) {
      console.log(data)
      this.$emit('addToFiled', data)
    },
    addToCandidate (data, type) {
      this.addLoading = true
      this.$http
        .get(this.$http.defaults.trainingAPI + `api/trainingBusClass/getById?id=` + this.classId)
        .then(response => {
          if (response.data.success === true) {
            let tableName = 'trainingBusRecommendedCandidate'
            if (type) {
              tableName = 'trainingBusOfficialCandidate'
            }
            let batchId = response.data.result.batchId
            let personNumber = response.data.result.personNumber
            let para = {
              batchId: batchId,
              classId: this.classId,
              deptId: this.deptId,
              name: data.name,
              idCardNo: data.idCardNo,
              age: data.age,
              unit: data.unit,
              job: data.job,
              level: data.level,
              partyMember: data.partyMember,
              jobDate: data.jobDate,
              selected: false
            }
            if (type) {
              para.type = type
              para.participation = (type === 1 ? 1 : 0)
            }
            if (type === 1) {
              this.$http
                .get(this.$http.defaults.trainingAPI + `api/trainingBusClass/getOfficialCandidateList?classId=` + this.classId)
                .then(response => {
                  if (response.data.success === true) {
                    let officialNum = response.data.result.filter(item => item.type === 1 && item.participation).length
                    if (officialNum < personNumber) {
                      this.addToCandidateSubmit(para, tableName)
                    } else {
                      this.$confirm('该班次培训人数为' + personNumber + '人，已添加参训人员' + officialNum + '人，是否继续添加？', '提示', {
                        type: 'warning'
                      }).then(() => {
                        this.addToCandidateSubmit(para, tableName)
                      }).catch(() => {
                        this.addLoading = false
                      })
                    }
                  } else {
                    this.addLoading = false
                    console.log('获取失败:' + response.data.message)
                    this.$message({
                      message: '获取失败:' + response.data.message,
                      type: 'error'
                    })
                  }
                }).catch((error) => {
                  this.addLoading = false
                  console.log(error)
                  this.$message({
                    message: '网络获取失败:' + error,
                    type: 'error'
                  })
                })
            } else {
              this.addToCandidateSubmit(para, tableName)
            }
          } else {
            this.addLoading = false
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.addLoading = false
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    addToCandidateSubmit (para, tableName) {
      this.$http.post(this.$http.defaults.trainingAPI + `api/` + tableName + `/save`, para).then(response => {
        console.log(response.data.success)
        this.addLoading = false
        if (response.data.success === true) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$emit('refreshRecommented')
        } else {
          console.log('操作失败:' + response.data.message)
          this.$message({
            message: '操作失败:' + response.data.message,
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '保存失败:' + error,
          type: 'error'
        })
        this.addLoading = false
      })
    },
    searchPrj () {
      this.pageNum = 1
      this.getList()
    },
    searchList () {},
    addPerson () {
      this.activeName = 'search'
    },
    moveData () {},
    handleEditPerson () {
      if (this.type === 'recommended') {
        this.personVisible = true
      } else if (this.type === 'official') {
        this.personVisible1 = true
      }
    },
    getList () {
      this.listLoading = true
      let team = null
      // if (this.userType === 2) {
      //   team = this.userTeam
      // } else {
      if (this.deptId) {
        team = this.deptId
      } else {
        team = this.filters.team
      }
      // }
      let para = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        team: team,
        unit: this.filters.unit,
        name: this.filters.name,
        idCardNo: this.filters.idCardNo
      }
      let url = 'api/trainingAdditionalPerson/queryByPage'
      this.$http
        .post(this.$http.defaults.trainingAPI + url, para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.personList = response.data.result.records

            if (this.viewtype === 1) {
              this.personList.forEach((item, index, arr) => {
                // if (!item.a0101) {
                //   arr[index].a0101 = item.name
                // }
              })
            }
            let allindex = 0
            this.personList.forEach((item, index, arr) => {
              arr[index].pindex = index + 1
              arr[index].allindex = 'p_' + allindex
              allindex++
              if (!item.id) {
                arr[index].id = 'p_' + item.filedId
              }
              if (item.children && item.children.length > 0) {
                item.children.forEach((it, idx, myarr) => {
                  myarr[idx].allindex = 'c_' + allindex
                  allindex++
                })
              }
            })
            this.totalnum = response.data.result.total
            console.log(this.personList.map(item => item.a0184))
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    inRoles (str) {
      let arr = JSON.parse(localStorage.getItem('Roles'))
      if (arr.indexOf(str) === -1) {
        return false
      } else {
        return true
      }
    },
    getDeptId () {
      let unitName = localStorage.getItem('unitName')
      let deptId = null
      switch (unitName) {
        case '干部一处':
          deptId = 1
          break
        case '干部二处':
          deptId = 2
          break
        case '干部三处':
          deptId = 3
          break
      }
      if (deptId) {
        this.userType = 2
        // this.userTeam = deptId
      }
      if (this.inRoles('ROLE_training')) {
        this.userType = 1
      }
      if (this.inRoles('ROLE_fusizhang')) {
        this.userType = 3
      }
      if (this.inRoles('ROLE_sizhang')) {
        this.userType = 4
        this.myAuth = 1
      }
    }
  },
  mounted () {
    this.getDeptId()
    if (localStorage.getItem('trainingAuth') === '1') {
      this.showManage = false
    } else {
      this.showManage = true
    }
    this.getList()
  }
}
</script>
<style>
  #trainIndex .wboxd .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  #trainIndex .wboxd .el-table td,
  #train .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  #trainIndex .el-table--border th,
  #train .el-table--border td {
    border-right: 1px solid #95B8E7;
  }
  #trainIndex .el-table th.is-leaf,
  #train .el-table td {
    border-bottom: 1px solid #95B8E7;
  }
  #trainIndex .el-table td{
    border-right: 1px solid #95B8E7;
    border-bottom: 1px solid #95B8E7;
  }
  .el-table .mark_class {
      background: rgb(253, 226, 226);
  }
</style>
<style scoped>
  #trainIndex h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  #trainIndex .el-pagination{
    float: left;
    padding:7px 10px;
  }
  #trainIndex .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  #trainIndex .wboxd{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  #trainEditTable .el-upload--text{
    float:left !important;
  }
  #trainEditTable .el-upload__tip{
    float:left !important;
    margin-left:5px;
    margin-top:0 !important;
  }
  #trainEditTable .el-upload-list--text{
    padding-top:5px;
    clear: both !important;
  }
  .el-table{
    border-top: 1px solid #95B8E7 !important;
  }
  .el-table--border th, .el-table--border td {
    border-right: 1px solid #95B8E7 !important;
  }
  .el-table th.is-leaf, .el-table td {
    border-bottom: 1px solid #95B8E7 !important;
    border-right: 1px solid #95B8E7 !important;
  }
  #trainEditTable .mytable{
    border-top: 1px solid #74A6CC;
    border-left: 1px solid #74A6CC;
    margin: 10px;
    width: calc(100% - 20px);
    font-size:var(--size14) !important;
    font-family: '宋体'
  }
  #trainEditTable .mytable th,
  #trainEditTable .mytable td{
    height: auto;
    padding: 10px;
    border-right: 1px solid #74A6CC;
    border-bottom: 1px solid #74A6CC;
    vertical-align:top;
    line-height: 150%;
  }
  #trainEditTable .mytable th{
    background:#C0DCF1;
    width:150px;
    vertical-align: middle;
  }
</style>
